//
//  PayCommodityViewController.m
//  cityStar
//
//  Created by Hancong on 14/12/25.
//  Copyright (c) 2014年 tiny. All rights reserved.
//

#import "PayCommodityViewController.h"
#import "TopPayTableViewCell.h"
#import "CommodityPayTableViewCell.h"
#import "BelowPayTableViewCell.h"
#import "IntegralViewController.h"
#import "DaijinquanViewController.h"
#import "PayWebViewController.h"
#import "WaresDetailViewController.h"

NSString *const topPayTableViewCellID = @"TopPayTableViewCellID";
NSString *const commodityPayTableViewCellID = @"CommodityPayTableViewCellID";
NSString *const belowPayTableViewCellID = @"BelowPayTableViewCellID";

@interface PayCommodityViewController ()<CloseCommidityTableViewCellDelegate,BelowPayTableViewCellDelegate>

@property (nonatomic, weak) IBOutlet UITableView *tableView;
//@property (nonatomic, weak) IBOutlet UIView *footView;
@property (nonatomic, weak) IBOutlet UIButton *btnSubmit;
@property (nonatomic, strong) TopPayTableViewCell *topPayCell;
@property (nonatomic, strong) BelowPayTableViewCell *belowPayCell;
@property (nonatomic, assign) int numOfCommidityCount;
@property (nonatomic, assign) BOOL isShowCommidity;
@property (nonatomic,strong) NSArray *requestArray;
@property (nonatomic,strong) NSString *address;

@end

@implementation PayCommodityViewController

-(instancetype)initWithCommodityArray:(NSArray *)commodityArray andAddress:(NSString *)address
{
    self = [super init];
    if (self) {
        self.requestArray = [[NSArray alloc]initWithArray:commodityArray];
        self.address = address;
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated
{
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    DLog(@"%@",self.parameters);
    self.title = @"确认订单";
    [self addBackButton];
    [self setUpTableViews];
    
    self.btnSubmit.clipsToBounds = YES;
    self.btnSubmit.layer.cornerRadius = 4;
    self.numOfCommidityCount = 2 ;
    self.isShowCommidity = NO;
}

-(void)setUpTableViews
{
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
//    self.tableView.tableFooterView = self.footView;
    [self.tableView registerNib:[TopPayTableViewCell nib] forCellReuseIdentifier:topPayTableViewCellID];
    [self.tableView registerNib:[CommodityPayTableViewCell nib] forCellReuseIdentifier:commodityPayTableViewCellID];
    [self.tableView registerNib:[BelowPayTableViewCell nib] forCellReuseIdentifier:belowPayTableViewCellID];
}

#pragma mark - Actions
-(IBAction)payToWebView_Touch:(id)sender
{
    [self.parameters setValue:@"1" forKey:@"pay_way"];
    [self.parameters setValue:@"1" forKey:@"place"];
    __weak typeof(self)weakSelf = self;
    [self.requestArray enumerateObjectsUsingBlock:^(BuycartGood *obj, NSUInteger idx, BOOL *stop) {
        NSString *keyID = [NSString stringWithFormat:@"goods[%li][id]",idx];
        [weakSelf.parameters setValue:obj.goods_id forKey:keyID];
        NSString *keyNumber = [NSString stringWithFormat:@"goods[%li][number]",idx];
        [weakSelf.parameters setValue:obj.number forKey:keyNumber];
    }];
    
    [HttpRequestManager postMethod:KInterface_getOrder parameters:self.parameters completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        DLog(@"%@",response);
        if (success) {
            __block float strAllPrice = 0;
            [self.requestArray enumerateObjectsUsingBlock:^(BuycartGood *obj, NSUInteger idx, BOOL *stop) {
                strAllPrice = [obj.price floatValue]*[obj.number intValue]+strAllPrice;
            }];
            
            NSString *order = response[@"value"][@"order"];
            PayWebViewController *payWebVC = [[PayWebViewController alloc]initWithOrder:order andPrice:[NSString stringWithFormat:@"%.2f",strAllPrice]];
            [self.navigationController pushViewController:payWebVC animated:YES];
        }else{
            [SVProgressHUD showErrorWithStatus:errMsg];
        }
    }];
}

#pragma mark - CloseCommidityTableViewCellDelegate
-(void)commidityColsedOrtxpend
{
    if (self.isShowCommidity == NO) {
        self.topPayCell.btnIsCloseCommodity.selected = YES;
        self.numOfCommidityCount = 2+(int)self.requestArray.count;
        self.isShowCommidity = YES;
        [self.tableView reloadData];
    }else{
        self.topPayCell.btnIsCloseCommodity.selected = NO;
        self.numOfCommidityCount = 2;
        self.isShowCommidity = NO;
        [self.tableView reloadData];
    }
//    self.topPayCell
}

#pragma mark - BelowPayTableViewCellDelegate
-(void)belowDaijinquanButtonBeTouched
{
    DaijinquanViewController *daijinquanVC = [[DaijinquanViewController alloc]init];
    [self.navigationController pushViewController:daijinquanVC animated:YES];

}

-(void)belowScoreButtonBeTouched
{
    IntegralViewController *integralVC = [[IntegralViewController alloc]init];
    [self.navigationController pushViewController:integralVC animated:YES];
}

#pragma mark - UITableViewDelegate and UITableViewDataSource
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.numOfCommidityCount > 2) {
    if (indexPath.row == 0) {
        self.topPayCell = [tableView dequeueReusableCellWithIdentifier:topPayTableViewCellID];
        __block float strAllPrice = 0;
        __block int allNumber = 0;
        [self.requestArray enumerateObjectsUsingBlock:^(BuycartGood *obj, NSUInteger idx, BOOL *stop) {
            strAllPrice = [obj.price floatValue]*[obj.number intValue]+strAllPrice;
            allNumber = [obj.number intValue]+allNumber;
        }];
        [self.topPayCell configWithTotal:[NSString stringWithFormat:@"%i",allNumber] andMoney:[NSString stringWithFormat:@"%.2f",strAllPrice]];
        
        self.topPayCell.selectionStyle = UITableViewCellSelectionStyleNone;
        self.topPayCell.delegate = self;
        return self.topPayCell;
    }else if (indexPath.row < self.numOfCommidityCount-1)
    {
    CommodityPayTableViewCell *commodityPayCell = [tableView dequeueReusableCellWithIdentifier:commodityPayTableViewCellID];
    commodityPayCell.selectionStyle = UITableViewCellSelectionStyleGray;
        DLog(@"%li",indexPath.row);
        BuycartGood *goodCart = self.requestArray[indexPath.row-1];
        [commodityPayCell configWithCommodity:goodCart];
    //[self.groupBuyTableViewCell configWithMessage:message];
    return commodityPayCell;
    }else{
        self.belowPayCell = [tableView dequeueReusableCellWithIdentifier:belowPayTableViewCellID];
        self.belowPayCell.labelAddress.text = self.address;
        self.belowPayCell.selectionStyle = UITableViewCellSelectionStyleNone;
        return self.belowPayCell;
    }
    }else{
        if (indexPath.row == 0) {
            self.topPayCell = [tableView dequeueReusableCellWithIdentifier:topPayTableViewCellID];
            if (self.topPayCell==nil) {
                self.topPayCell=[[TopPayTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:topPayTableViewCellID];
            }
            __block float strAllPrice = 0;
            __block int allNumber = 0;
            [self.requestArray enumerateObjectsUsingBlock:^(BuycartGood *obj, NSUInteger idx, BOOL *stop) {
                strAllPrice = [obj.price floatValue]*[obj.number intValue]+strAllPrice;
                allNumber = [obj.number intValue]+allNumber;
            }];
            [self.topPayCell configWithTotal:[NSString stringWithFormat:@"%i",allNumber] andMoney:[NSString stringWithFormat:@"%.2f",strAllPrice]];
            
            self.topPayCell.selectionStyle = UITableViewCellSelectionStyleNone;
            self.topPayCell.delegate = self;
            return self.topPayCell;
        }else{
            self.belowPayCell = [tableView dequeueReusableCellWithIdentifier:belowPayTableViewCellID];
            if ([[self.parameters objectForKey:@"deliver"] intValue] == 1) {
                self.belowPayCell.labelpeisongType.text = @"线下自提";
            }else{
                self.belowPayCell.labelpeisongType.text = @"快递送货上门";
            }
            if ([[self.parameters objectForKey:@"range"] intValue] == 0) {
                self.belowPayCell.labelpeisongTime.text = @"均可";
            }else if([[self.parameters objectForKey:@"range"] intValue] == 1){
                self.belowPayCell.labelpeisongTime.text = @"上午（12点前）";
            }else{
                self.belowPayCell.labelpeisongTime.text = @"下午（17点前）";
            }
            self.belowPayCell.labelAddress.text = self.address;
            self.belowPayCell.delegate = self;
            self.belowPayCell.selectionStyle = UITableViewCellSelectionStyleNone;
            return self.belowPayCell;
        }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.numOfCommidityCount > 2) {
        if (indexPath.row == 0){
            return [TopPayTableViewCell heightOfTableCell];
        }else if (indexPath.row <self.numOfCommidityCount){
            return [CommodityPayTableViewCell heightOfTableCell];
        }else{
            return [BelowPayTableViewCell heightOfTableCell];
        }
    }else{
        if (indexPath.row == 0){
            return [TopPayTableViewCell heightOfTableCell];
        }else{
            return [BelowPayTableViewCell heightOfTableCell];
        }
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.numOfCommidityCount;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.numOfCommidityCount > 2) {
        if (0 < indexPath.row < self.numOfCommidityCount-1)
        {
            BuycartGood *goodCart = self.requestArray[indexPath.row-1];
            WaresDetailViewController *waresDetailViewController = [[WaresDetailViewController alloc]initWithCommodityID:goodCart.goods_id];
            [self.navigationController pushViewController:waresDetailViewController animated:YES];
        }
    }
    [tableView reloadData];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.

}
#pragma mark - UIKeyBoard Change Frame Notificatin Method
- (void)keyboardWillShow:(NSNotification *)notification
{
    NSDictionary *userInfo = [notification userInfo];
    CGRect keyboardFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    self.tableView.height = CGRectGetHeight(AppBounds)-64-CGRectGetHeight(keyboardFrame);
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    self.tableView.height = CGRectGetHeight(AppBounds) - 44 - 64 -20;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
